package com.cetc;

import com.cetc.domain.Animal;
import com.cetc.domain.Person;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @Classname ReflectionTest02
 * @Description 通过反射调用指定类
 * @Date 2022/12/13 20:13
 * @Created by louzhuangxi
 */
public class ReflectionTest02 {

    /**
     * 操作运行时类的属性
     */
    @Test
    public void test01() throws Exception {
        Class<Animal> aClass = Animal.class;
        Animal animal = aClass.newInstance();
        Field id = aClass.getDeclaredField("id");
        System.out.println(id);

        id.set(animal, 1);
        int pid = (int) id.get(animal);
        System.out.println(pid);

        Field age = aClass.getDeclaredField("age");
        age.setAccessible(true);
        age.set(animal, 20);
        int pName = (int) age.get(animal);
        System.out.println(pName);
    }

    /**
     * 操作运行时类的方法
     */
    @Test
    public void test02() throws Exception {
        Class<Animal> aClass = Animal.class;
        Animal animal = aClass.newInstance();
        Method method = aClass.getDeclaredMethod("show", String.class);
        method.setAccessible(true);
        Object invoke = method.invoke(animal, "中国");
        System.out.println(invoke);

        //调用静态方法时不需要传入对象,因为每个对象调用静态方法是一样的
        Method showDesc = aClass.getDeclaredMethod("showDesc", String.class);
        showDesc.setAccessible(true);
        Object o = showDesc.invoke(null, "我是一个好人");
        System.out.println(o);
    }

    /**
     * 获取指定构造器创建对象
     */
    @Test
    public void test03() throws Exception {
        Class<Animal> aClass = Animal.class;
        Constructor<Animal> declaredConstructor = aClass.getDeclaredConstructor(String.class);
        declaredConstructor.setAccessible(true);

        Animal instance = declaredConstructor.newInstance("张三");
        System.out.println(instance.getName());
    }
}
